﻿$.ajaxSettings.traditional = true;

var __jquiCfg = {
    focusBindings: {},
    calendarImage: "/content/images/admin/schedule16.gif"
};


$.applyJqui = function (context)
{
    if (!context)
        return;

    $(".jqui-buttons-bar", context).each(function (i, e)
    {
        var el = $(e);
        if (!el.children().length)
            el.hide();
    });

    $(".jqui-field-group[data-view-only]", context).each(function (i, e)
    {
        $(e).setDataFieldGroupViewOnly(true);
    });

    $(".jqui-ajax-panel", context).each(function (i, e)
    {
        var el = $(e);
        if ((el.attr("data-deferred") || "").toLowerCase() != "true")
            $(e).ajaxPanelLoad();
    });
};

var jqui_wrapLoadMethod = function ()
{
    $.fn.originalLoad = $.fn.load;
    $.fn.load = function ()
    {
        var args = arguments;
        if (args && args.length && $.isFunction(args[args.length - 1]))
        {
            var callback = args[args.length - 1];
            args[args.length - 1] = function ()
            {
                $.applyJqui(this);
                callback.apply(this, arguments);
            };
        }
        else
        {
            args[args.length] = function ()
            {
                $.applyJqui(this);
            };
            args.length = args.length + 1;
        }
        $.fn.originalLoad.apply(this, args);
    };
};
jqui_wrapLoadMethod();

var jqui_wrapValMethod = function ()
{
    var originalMethod = $.fn.val;
    $.fn.val = function ()
    {
        if (!arguments || !arguments.length)
        {
            var _this = $(this);
            var result = originalMethod.apply(this, arguments);
            var ifempty = _this.attr('ifempty');
            if (ifempty && ifempty.length && ifempty == result)
                return "";
            return result;
        }
        return originalMethod.apply(this, arguments);
    };
    $.fn.storedVal = originalMethod;
};
jqui_wrapValMethod();

$(function ()
{
    $.applyJqui($("body"));

    $(".jqui-help-icon .ui-icon")
        .live("mouseenter", function () { $(this).parent().addClass("ui-state-highlight"); })
        .live("mouseout", function () { $(this).parent().removeClass("ui-state-highlight"); });

    $(".jqui-searchbox-input").live("keypress", function (e)
    {
        var _this = $(this);
        if (e.which == '13')
        {
            _this.parent().find("button:first").click();
        }
    });

    $(".jqui-searchbox button:first").live("click", function (e)
    {
        var input = $(this).parent().find("input:first");
        setTimeout(function ()
        {
            input.focus();
        }, 50);
    });

    $(".jqui-button").live("click", function (e) { e.preventDefault(); });

    $(".jqui-link, .jqui-button[data-link-behavior]").live("click", function (e)
    {
        var _this = $(this);
        var behavior = (_this.attr("data-link-behavior") || "").toLowerCase();
        var href = _this.attr("href");
        if (!behavior || !behavior.length || behavior == "default")
            return;
        e.preventDefault();
        if (behavior == "openonnewdialog")
            $.openDialog(href);
        else if (behavior == "openonnewdialogrefresh")
        {
            $.openDialog(href, null, function (result)
            {
                var ajaxPanel = _this.getAjaxPanelElement();
                if (ajaxPanel && ajaxPanel.length)
                    ajaxPanel.ajaxPanelUpdate();
                else
                {
                    window.location.reload();
                }
            });
        }
        else if (behavior == "loadoncurrentdialog")
            _this.loadDialog(href);
        else if (behavior == "loadoncurrentajaxpanel")
            _this.ajaxPanelLoad(href);
        else if (behavior == "openonolddialog")
        {
            $.colorbox({ href: href });
        }
        else if (behavior == "loadoncurrent")
        {
            var ajaxPanel = _this.getAjaxPanelElement();
            if (ajaxPanel && ajaxPanel.length)
                ajaxPanel.ajaxPanelLoad(href);
            else
            {
                var dialog = _this.getDialogElement();
                if (dialog && dialog.length)
                    dialog.loadDialog(href);
            }
        }
    });

    $(".jqui-dialog-close-link")
        .live("mouseenter", function () { $(this).addClass("ui-state-hover"); })
        .live("mouseout", function () { $(this).removeClass("ui-state-hover"); })
        .live("mousedown", function () { $(this).addClass("ui-state-active"); })
        .live("mouseup", function () { $(this).removeClass("ui-state-active"); })
        .live("click", function (e) { e.preventDefault(); $.closeDialog() });

    $(".jqui-date-frag, .jqui-time-frag").live("blur change", function ()
    {
        var _this = $(this);
        var sourceEid = _this.attr("data-source");
        var parent = _this.parent();
        var dataSourceSelector = "[data-source=" + sourceEid + "]";
        var date = parent.find(".jqui-date-frag" + dataSourceSelector).val();
        var hour = parent.find(".jqui-time-frag" + dataSourceSelector).val();
        var val = utils.formatDateString(date + " " + hour, true);
        parent.find("[data-eid=" + sourceEid + "]").val(val);
    });

    $(".jqui-pager-button").live("click", function ()
    {
        var pager = $(this).getPagerElement();
        if (pager && pager.length)
        {
            var updateAjax = (pager.attr('data-update-current-container') || "").toLowerCase() !== "false";
            if (updateAjax)
            {
                var paramName = pager.attr('data-ajax-param-name') || "page";
                var params = {};
                params[paramName] = $(this).attr('data-page');
                $(this).ajaxPanelUpdate(params);
            }
        }
    });

    $(".jqui-data-table .sel-row-check").live("click", function ()
    {
        var checked = $(this).is(":checked");
        if (checked)
            $(this).parents("tr:first").addClass("ui-state-hover");
        else
            $(this).parents("tr:first").removeClass("ui-state-hover");
    });

    $(".jqui-data-table .sel-row-check-all").live("click", function ()
    {
        var checked = $(this).is(":checked");
        var target = $(this).parents(".jqui-data-table:first").find("input[name=" + $(this).attr('data-target-name') + "]");
        if (checked)
        {
            target.each(function (i, e)
            {
                $(e).attr('checked', 'checked')
                    .parents("tr")
                      .first()
                      .addClass("ui-state-hover");
            });
        }
        else
        {
            target.removeAttr('checked');
            target.each(function (i, e)
            {
                $(e).parents("tr").first().removeClass("ui-state-hover");
            });
        }
    });
});

/*
* widgets initialization
*/

$.checkAjaxTab = function (pnl)
{
    if (pnl.hasClass("jqui-ajax-panel") && pnl.attr("data-ajax-panel-loaded") !== "1")
    {
        pnl.attr("data-ajax-panel-loaded", "1");
        pnl.ajaxPanelLoad();
    }
};

$.fn.createTabs = function ()
{
    var _this = $(this).tabs({
        select: function (event, ui)
        {
            $.checkAjaxTab($(ui.panel));
        }
    });

    var idx = _this.tabs('option', 'selected');
    $.checkAjaxTab($(_this.find(".ui-tabs-panel").get(idx)));

    _this.find('.ui-tabs-nav')
        .removeClass('ui-corner-all')
        .addClass('ui-corner-top');

    _this.find('.ui-tabs')
        .removeClass('ui-widget-content');
};


/*
* Framework methods
*/
$.fn.thisOrParent = function (selector)
{
    var _this = $(this);
    if (_this.is(selector))
        return _this;
    else
    {
        result = _this.parents(selector);
        if (result.length)
            return $(result[0]);
    }
};

$.fn.getById = function (id)
{
    var _this = $(this);
    if (_this.attr('id') == id) return _this;
    else return _this.find('#' + id);
};


$.fn.getContextElement = function (ctx)
{
    return $(this).thisOrParent("[data-clt-ctx=" + ctx + "]");
};

$.fn.getContextValue = function (ctx)
{
    var el = $(this).getContextElement(ctx);
    if (el && el.length)
        return el.attr("data-clt-ctx-value");
};

$.fn.setContextValue = function (ctx, value, local)
{
    var el = $(this).getContextElement(ctx);
    if (!el || !el.length || !local)
        el = $(this);
    el.attr("data-clt-ctx-value", value);
};

$.fn.clearUpdateState = function ()
{
    return $(this).removeClass("updating updated");
};

$.fn.showUpdating = function ()
{
    return $(this).clearUpdateState().addClass("updating");
};

$.fn.showUpdated = function ()
{
    var el = $(this).clearUpdateState().addClass("updated");
    setTimeout(function ()
    {
        el.removeClass("updated");
    }, 4000);
};

var initDialog = function ()
{
    var _zIndex = 5000;
    var _dialogStack = [];

    var checkBodyScroll = function ()
    {
        var body = $("body");
        if (_dialogStack.length)
        {
            var top = body.scrollTop();
            body.css("overflow", "hidden");
            body.scrollTop(top);
        }
        else
        {
            body.css("overflow", "").css("overflow-y", "").css("overflow-x", "");
        }
    };

    var removeFromStack = function (info)
    {
        for (var i = 0, item; (item = _dialogStack[i]); i++)
        {
            if (item.id == info.id)
            {
                _dialogStack.splice(i, 1);
                return;
            }
        }
    };

    $.createDialog = function ()
    {
        var overlay = $('<div class="ui-widget-overlay jqui-dialog-overlay"><div>');
        var dialog = $('<div class="jqui-dialog"><table class="jqui-dialog-container"><tbody><tr><td class="jqui-dialog-content-holder"></td></tr></tbody></table></div>');
        overlay.css("z-index", ++_zIndex);
        overlay.appendTo("body");
        dialog.css("z-index", ++_zIndex);
        var id = utils.guid();
        dialog.attr("id", id);
        dialog.appendTo("body");
        dialog.scroll(function (e)
        {
            e.stopPropagation();
            e.stopImmediatePropagation();
        });
        var info = {
            dialog: dialog,
            overlay: overlay,
            content: dialog.find(".jqui-dialog-content-holder:first"),
            zIndex: _zIndex,
            id: id
        };
        dialog.data("jqui-dialog-data", info);
        _dialogStack.push(info);
        checkBodyScroll();
        return info;
    }

    $.openDialog = function (url, params, closeCallback, targetDialogEl)
    {
        if (targetDialogEl)
            var info = $(targetDialogEl).getDialogData();
        if (!info)
            var info = $.createDialog();
        info.url = url;
        info.params = params || {};
        info.callback = closeCallback || info.callback;

        var holder = $("<div style='position: absolute; width: 1px; height: 1px; overflow: scroll; visibility: hidden;'></div>").appendTo("body");

        holder.originalLoad(url, info.params, function ()
        {
            $("<div class='ui-helper-clearfix'></div>").appendTo(holder);
            $.applyJqui(holder.get(0));
            info.content.children().remove();
            var firstEl = holder.find(":first");
            var firstW = firstEl.width();
            if (firstW > 30)
                firstEl.width(firstW);
            info.content.append(holder.children());
            $.setFocusOnFirstField(info.content);
            holder.remove();
        });
    };

    $.loadDialog = function (url, params, targetDialogEl)
    {
        $.openDialog(url, params, null, targetDialogEl || $.getOpenedDialogElement());
    };

    $.updateDialog = function (params, targetDialogEl)
    {
        var info = $(targetDialogEl).getDialogData();
        if (info)
            $.loadDialog(info.url, $.extend({}, info.params, params), info.dialog);
    };

    $.closeDialog = function (returnValue, dialogElement)
    {
        if (dialogElement)
            info = $(dialogElement).getDialogData();
        else
            var info = $.getOpenedDialogElement();
        if (info)
        {
            removeFromStack(info);
            if (info.callback)
                info.callback.call(info.dialog.get(0), returnValue || info.returnValue, info.content);
            info.dialog.remove();
            info.overlay.remove();
            checkBodyScroll();
        }
    };

    $.getOpenedDialogElement = function ()
    {
        return _dialogStack.length ? _dialogStack[_dialogStack.length - 1] : undefined;
    };

    $.fn.getDialogElement = function ()
    {
        return $(this).thisOrParent(".jqui-dialog");
    };

    $.fn.getDialogData = function ()
    {
        return $(this).getDialogElement().data("jqui-dialog-data");
    };

    $.fn.loadDialog = function (url, params)
    {
        $.loadDialog(url, params, $(this).getDialogElement());
        return this;
    };

    $.fn.updateDialog = function (params)
    {
        $.updateDialog(params, $(this).getDialogElement());
        return this;
    };

    $.fn.closeDialog = function (returnValue)
    {
        $.closeDialog(returnValue, $(this).getDialogElement());
        return this;
    };

    $.fn.setDialogReturn = function (returnValue)
    {
        var info = $(this).getDialogData();
        if (info)
            info.returnValue = returnValue;
        return this;
    };
};
initDialog();
initDialog = undefined;

$.fn.getFieldElement = function ()
{
    return $(this).thisOrParent(".jqui-input");
};

$.fn.setDataFieldError = function (msg)
{
    var el = $(this).getFieldElement();
    if (!el) return;
    el.addClass("error");
    var errorEl = el.find(".error-msg");
    if (!errorEl.length)
    {
        //wrap dos inputs
        el.find(":input").wrapAll("<span class='input-wrap'/>");
        errorEl = $("<span class='error-msg'/>").appendTo(el.find(".input-wrap"));
    }
    errorEl.text(msg)
    return this;
};

$.fn.clearDataFieldError = function ()
{
    return this.each(function ()
    {
        var el = $(this).getFieldElement();
        if (!el) return;
        el.removeClass("error").find(".error-msg").text("")
    });
};

$.fn.clearAllDataFieldErrors = function ()
{
    $(this).getDataFieldGroupElement().find(".jqui-input").each(function (i, e)
    {
        $(e).getFieldElement().clearDataFieldError();
    });
    return this;
};

$.fn.getFieldTargetInput = function ()
{
    var field = $(this).getFieldElement();
    if (field.is(":input"))
        return field;
    return field.find(":input:first");
};


$.fn.validateDataField = $.fn.validateField = function ()
{
    $(this).clearDataFieldError();
    var el = $(this).getFieldTargetInput();
    if ((el.attr("data-validate-required") || "").toLowerCase() == "true")
    {
        var result = $(this).validateDataFieldRequired();
        if (!result) return false;
    }
    return true;
};

$.fn.validateDataFieldRequired = function ()
{
    var el = $(this).getFieldTargetInput();
    if ((el.val() || "").trim() == "")
    {

        var msg = el.attr("data-validation-required-message");
        if (!msg || !msg.length)
            msg = "Este campo deve ser informado.";
        el.setDataFieldError(msg);
        return false;
    }
    return true;
};

$.fn.validateFieldGroup = function ()
{
    var result = true;
    $(this).getDataFieldGroupElement().find(".jqui-input").each(function (i, e)
    {
        result = result && $(e).getFieldElement().validateDataField();
    });
    return result;
};

$.fn.getDataFieldGroupElement = function ()
{
    return $(this).thisOrParent(".jqui-field-group");
};

$.fn.setDataFieldGroupViewOnly = function (viewOnly)
{
    var group = $(this).getDataFieldGroupElement();
    var fields = group.find(".jqui-input");
    if (viewOnly)
    {
        fields.addClass("view-only").find("input").attr("readonly", "readonly");
        fields.find("select").attr("disabled", "disabled");
        group.addClass("view-only");
    }
    else
    {
        fields.removeClass("view-only");
        group.removeClass("view-only");
        fields.find("input").removeAttr("readonly", "readonly");
        fields.find("select").removeAttr("disabled", "disabled");
    }
};

$.fn.submitDataFieldGroup = function (url, params, callback)
{
    if ($.isFunction(params))
    {
        callback = params;
        params = undefined;
    }
    var el = $(this).getDataFieldGroupElement();
    if (el.length)
    {
        var fields = el.serializeFields(params);
        $.post(url, fields, function (result)
        {
            if (!result)
                result = { success: false, error: true, errorMessage: "Request failed." };

            el.clearAllDataFieldErrors();

            if (result.hasErrors)
            {
                $.alertUser("O formulário não pode ser salvo.", true);
                //mensagem de erro nos campos.
                if (result.errorMessage)
                {
                    setTimeout(function ()
                    {
                        alert(result.errorMessage);
                    }, 1000);
                }
                var vm = result.validationMessages;
                if (vm)
                {
                    var firstErrorEl = undefined;
                    for (var it in vm)
                    {
                        if (vm.hasOwnProperty(it))
                            var input = el.getById(it);
                        if (input.length)
                        {
                            input.setDataFieldError(vm[it]);
                            if (!firstErrorEl)
                                firstErrorEl = input;
                        }
                        else
                            setTimeout(function ()
                            {
                                alert(vm[it]);
                            }, 1000);
                    }
                }
            }
            else
            {
                $.alertUser("Formulário enviado");
            }

            if (firstErrorEl)
            {
                setTimeout(function ()
                {
                    firstErrorEl.parent().find("input:enabled:visible").not("button").first().focus();
                }, 100);
            }
            if (callback)
                callback.call(el.get(0), result);
        });
    };
    return this;
};

createUiAlert = function ()
{
    var timer = 0, containerEl, textEl;

    $.alertUser = function (msg, error)
    {
        if (timer)
        {
            clearTimeout(timer);
            containerEl.fadeOut();
        }
        if (!containerEl)
        {
            textEl = $("<span class='alert-text'></span>");
            containerEl = $("<div class='jqui-user-alert'></div>")
                .append("<span class='ui-icon ui-icon-info'></span>")
                .append(textEl)
                .appendTo("body");
        }

        setTimeout(function ()
        {
            if (error)
                containerEl.removeClass("ui-state-highlight").addClass("ui-state-error");
            else
                containerEl.removeClass("ui-state-error").addClass("ui-state-highlight");

            textEl.text(msg);
            containerEl.show().css("visibility", "hidden");
            setTimeout(function ()
            {
                containerEl.hide();
                containerEl.css("visibility", "visible");
                containerEl.fadeIn();
            }, 1);
        }, 300);

        timer = setTimeout(function ()
        {
            timer = 0;
            containerEl.fadeOut('slow');
        }, 5000);
    };
};
createUiAlert();

$.fn.getAjaxPanelElement = function ()
{
    return $(this).thisOrParent(".jqui-ajax-panel");
};

$.fn.ajaxPanelLoad = function (url, params, callback)
{
    var el = $(this).getAjaxPanelElement();
    if (!url)
        url = el.attr("data-source-url");
    else
        el.attr("data-source-url", url);

    if ($.isFunction(params))
    {
        callback = params;
        params = undefined;
    }

    var currParams = el.data("_ajaxPanelParams");
    if (!currParams)
        currParams = {};
    params = $.extend(currParams, params || {});
    el.data("_ajaxPanelParams", params);

    el.block();
    el.load(url, params, function (result)
    {
        if (callback) callback.call(el.get(0), result);
    });
};

$.fn.ajaxPanelUpdate = function (params, callback)
{
    $(this).ajaxPanelLoad(null, params, callback);
};

$.setFocusOnFirstField = function (el)
{
    setTimeout(function ()
    {
        el.find(":input:visible:enabled").not("[readonly]").not("button").first().focus();
    }, 30);
};

$.fn.menuSelect = function (callback)
{
    var el = $(this).thisOrParent(".jqui-menu");
    if (el)
        el.bind("menuselect", callback);
};

$.fn.serializeFields = function (exceptions)
{
    var result = [];
    exceptions = exceptions || {};
    $(this).find(":input").each(function (idx, el)
    {
        var _el = $(el);
        var val = _el.val();
        var name = _el.attr('name');
        if (name == "" || exceptions.hasOwnProperty(name))
            return;
        if (_el.hasClass("custom-mask"))
            val = utils.filterDigits(val);
        result.push({ name: _el.attr("name"), value: val });
    });
    for (var p in exceptions)
        if (exceptions.hasOwnProperty(p))
            result.push({ name: p, value: exceptions[p] });
    return result;
};

$.fn.getPagerElement = function ()
{
    return $(this).thisOrParent(".jqui-pager");
};

// wizard
$(function ()
{
    $(".jqui-wizard #wizard-back").live("click", function ()
    {
        var _this = $(this);
        if (_this.is(":disabled"))
            return;
        $(this).wizardBack();
    });

    $(".jqui-wizard #wizard-cancel").live("click", function ()
    {
        if (confirm('Cancelar o assistente?'))
        {
            $(this).closeDialog();
        }
    });

    $(".jqui-wizard #wizard-finish").live("click", function ()
    {
        $(this).closeDialog();
    });
});

$.fn.getWizardElement = function ()
{
    return $(this).thisOrParent(".jqui-wizard");
};

$.fn.wizardBegin = function (url)
{
    $(this).wizardPostNext(url);
    return this;
};

$.fn.setWizardState = function (key, value)
{
    var wizard = $(this).getWizardElement();
    var data = wizard.data('__wizard_state__');
    if (!data)
        wizard.data('__wizard_state__', (data = {}));
    data[key] = value;
    return this;
};

$.fn.getWizardState = function (key)
{
    var wizard = $(this).getWizardElement();
    var data = wizard.data('__wizard_state__');
    if (data && key)
        return data[key];
    return data;
};

$.fn.wizardPostNext = function (url, params)
{
    var wizard = $(this).getWizardElement();
    if (!wizard)
        alert("Wizard not found");

    //criar o container desta pagina
    var page = $("<div/>")
        .addClass("jqui-wizard-page-holder ui-helper-hidden");

    page.appendTo(wizard);

    var data = wizard.data('__wizard_state__');
    if (!params)
        params = data;
    else if (data)
        params = $.extend(data, params);

    // delay para atualizar a ui
    setTimeout(function ()
    {
        // carregar o conteudo
        page.load(url, params, function (data)
        {
            // recuperar o id da pagina
            var innerPage = page.find(".jqui-wizard-page").first();
            var pageId = innerPage.attr("id");
            page.attr("data-page-id", pageId);
            page.wizardSelectPage(pageId);
            innerPage.trigger('wizardPageReady');
        });
    }, 1);

    return this;
};

$.fn.wizardPageReady = function (fn)
{
    if ($.isFunction(fn))
        $(this).bind('wizardPageReady', fn);
    else
        $(this).trigger('wizardPageReady');
};

$.fn.wizardPostState = function (url, params, callback)
{
    return $(this).wizardSendState(url, params, callback, 'post');
};

$.fn.wizardSendState = function (url, params, callback, method)
{
    var wizard = $(this).getWizardElement();

    if (params && $.isFunction(params))
    {
        callback = params;
        params = undefined;
    }
    var data = wizard.data('__wizard_state__');
    if (!params)
        params = data;
    else if (data)
        params = $.extend(data, params);

    if (method == 'post')
        $.post(url, params, callback);
    else
        $.get(url, params, callback);
};


$.fn.wizardBack = function ()
{
    var wizard = $(this).getWizardElement();
    var children = wizard.children();
    if (children.length > 1)
    {
        //penultimo
        wizard.wizardSelectPage(children.eq(-2).attr('data-page-id'));
    }
    return this;
};

$.fn.wizardSelectPage = function (pageId)
{

    var wizard = $(this).getWizardElement();
    //esconder todos os filhos;
    wizard.children().addClass("ui-helper-hidden");

    var page;
    if (typeof pageId === "string")
    // procurar pelo page id
        page = wizard.children("[data-page-id=" + pageId + "]").first();
    else
        page = pageId;
    if (page.length)
    {
        // remover todos os que vierem depois
        page.nextAll().remove();
        // selecionar a pagina
        page.removeClass("ui-helper-hidden");
        // verificar o botão back
        var backButton = wizard.find("#wizard-back").first();
        var chldrenCount = wizard.children().length;
        if (chldrenCount <= 1)
            backButton.button("option", "disabled", true);
        else
            backButton.button("option", "disabled", false);
    };
    return this;
};

$.fn.getInputValues = function (name)
{
    var res = [];
    $(this).find(":input[name=" + name + "]").each(function (i, e)
    {
        res[i] = $(e).val();
    });
    return res;
};

// data table

$.fn.getDataTableElement = function ()
{
    return $(this).thisOrParent(".jqui-data-table");
};

$.fn.getSelectedRowValues = function (checkName)
{
    var table = $(this).getDataTableElement();
    var res = []
    table.find("input[name=" + checkName + "]:checked").each(function (i, e)
    {
        res[i] = $(e).val();
    });
    return res;
};


// tree item
$.fn.getTreeItemElement = function ()
{
    return $(this).thisOrParent(".jqui-tree-item");
};

$.fn.getTreeItemCheckElement = function ()
{
    return $(this).children(".jqui-tree-item-inner").find(".jqui-tree-item-check").first();
};

$.fn.getParentTreeItemElement = function ()
{
    var current = $(this).getTreeItemElement();
    if (!current)
        return null;
    return current.parents(".jqui-tree-item").first();
};

$.fn.getTreeItemChildrenElements = function ()
{
    var current = $(this).getTreeItemElement();
    if (!current) return null;
    return current.children(".sub-tree").children(".jqui-tree-item");
};

$.fn.getSelectedTreeValues = function ()
{
    var res = [];
    $(this).find(".jqui-tree-item-check:checked").each(function (i)
    {
        res[i] = $(this).val();
    });
    return res;
};

$.fn.setTreeItemCheck = function (checked, parentBehavior, force, recursive)
{
    var item = $(this).getTreeItemElement();
    var cb = item.getTreeItemCheckElement();
    var cbSt = cb.is(":checked");
    if (cbSt != checked)
    {
        if (!checked)
            cb.removeAttr("checked");
        else
            cb.attr("checked", "checked").change();
    }
    else if (!force)
        return;
    var behavior = item.attr('data-tree-check-behavior');
    if (!behavior || !behavior.length || behavior.toLowerCase() === "inherit")
    {
        behavior = parentBehavior;
        if (!behavior)
        {
            parentBehavior = item.parents('.jqui-tree-item[data-tree-check-behavior]').not('[data-tree-check-behavior="Inherit"]');
            if (parentBehavior.length)
                behavior = parentBehavior.attr("data-tree-check-behavior");
        }
    }
    if (!behavior)
        behavior = 'All';
    behavior = behavior.toLowerCase();
    var all = behavior == "all";
    var propBottom = behavior == "toptobottom";
    if (all || propBottom)
    {
        if (!checked)
        {
            //remover todos os checks de todos os filhos.
            item.children("ul").find(".jqui-tree-item-check:checked").each(function ()
            {
                $(this).setTreeItemCheck(false, behavior, false, true);
            });
        }
        else
        {
            // colocar o check onde não existe
            item.children("ul").find(".jqui-tree-item-check").not(":checked").each(function ()
            {
                $(this).setTreeItemCheck(true, behavior, false, true);
            });
        }
        if (all && !recursive)
        {
            var parent = item.getParentTreeItemElement();
            if (parent && parent.length)
            {
                var pitems = parent.getTreeItemChildrenElements();
                var pcheck = parent.getTreeItemCheckElement();
                var pchecked = pcheck.is(":checked");
                if (pitems.length)
                {
                    if (pitems.find(":checked").length)
                    {
                        if (!pchecked)
                            pcheck.attr("checked", "checked").change();
                    }
                    else if (pchecked)
                        pcheck.removeAttr("checked").change();
                }
            }
        }
    }
};

$(function ()
{
    $(".jqui-tree-item-inner > .ui-icon")
        .live("click", function (e)
        {
            e.stopPropagation();
            var item = $(this).getTreeItemElement();
            var ul = item.children("ul").first();
            if (ul.is(":visible"))
            {
                ul.hide();
                $(this).removeClass('ui-icon-triangle-1-se').addClass('ui-icon-triangle-1-e');
            }
            else
            {
                //ul.removeClass('ui-helper-hidden');
                ul.show();
                $(this).removeClass('ui-icon-triangle-1-e').addClass('ui-icon-triangle-1-se');
            }
        });

    $(".jqui-tree-item-check").live("click", function ()
    {
        var _this = $(this);
        _this.setTreeItemCheck(_this.is(":checked"), undefined, true);
    });

    $(".jqui-tree-item-inner")
        .live("mouseenter", function ()
        {
            $(this).addClass("ui-state-hover").removeClass("ui-state-default");
        })
        .live("mouseleave", function ()
        {
            $(this).removeClass("ui-state-hover").addClass("ui-state-default");
        });


});